package com.swt.gap.util.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 请填写说明
 *
 * @author sx
 * @date 2020/1/21 16:02
 */
public class HeaderAndDataListener extends AnalysisEventListener<Map<Integer,String>> {
    private List<String> headerList = new ArrayList<>();
    private List<List<String>> dataList = new ArrayList<>();
    private List<Map<String, String>> fieldsMap = new ArrayList<>();

    /**
     * 起始行号，包含
     */
    private Integer startRowIndex;
    /**
     * 截止行号，包含
     */
    private Integer endRowIndex;

    public HeaderAndDataListener() {
    }

    public HeaderAndDataListener(Integer startRowIndex) {
        this.startRowIndex = startRowIndex;
    }

    public HeaderAndDataListener(Integer startRowIndex, Integer endRowIndex) {
        this.startRowIndex = startRowIndex;
        this.endRowIndex = endRowIndex;
    }


    @Override
    public void invoke(Map<Integer, String> integerStringMap, AnalysisContext analysisContext) {
        Integer currentRowIndex = analysisContext.readRowHolder().getRowIndex();
        boolean isInRange = (startRowIndex == null || currentRowIndex >= startRowIndex) && (endRowIndex == null || currentRowIndex <= endRowIndex);
        if (isInRange) {
            List<String> row = new ArrayList<>();
            integerStringMap.forEach((k, v) -> row.add(v));
            dataList.add(row);
        }
        if (currentRowIndex > 0) {
            Map<String, String> fieldMap = new HashMap<>();
            integerStringMap.forEach((k, v) -> {
                fieldMap.put(headerList.get(k), v);
                fieldsMap.add(fieldMap);
            });

        }

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }

    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        headMap.forEach((k,v) -> headerList.add(v));
    }

    public List<String> getHeaderList() {
        return headerList;
    }

    public List<List<String>> getDataList() {
        return dataList;
    }

    public List<Map<String, String>> getFieldsMap() {
        return fieldsMap;
    }
}
